const sequelize =require("../config/database") ;

const checkFile=async (hash) => {
    try {
        const [results, metadata] = await sequelize.query(`SELECT * FROM file WHERE file_hash ="${hash}"`);
        if (results.length===0){
            return {data: {isHas:false, url: ""}, err:""}
        }else {
            return {data: {isHas:true, url: results[0].url}, err:""}
        }
    }catch (err) {
      return   {data: {}, err:JSON.stringify(err)}
    }

}
const checkSlice =async (data) => {
    try {
        const [results, metadata] = await sequelize.query(`SELECT * FROM slice WHERE file_hash ="${data.file_hash}" AND chunk_index =${data.chunk_index}`);
        if (results.length===0){
            return {data: {isHas:false}, err:""}
        }else {
            return {data: {isHas:true}, err:""}
        }
    }catch (err) {
        return   {data: {}, err:JSON.stringify(err)}
    }

}

const insertSliceFile=async (data)=>{
    try {
        const [results, metadata] = await sequelize.query(`INSERT INTO slice (file_hash,chunk_index,url)VALUES  ("${data.file_hash}","${data.chunk_index}","${data.url}")`);
        return {err: ""}
    }catch (err) {
        return {err: JSON.stringify(err)}
    }

}
const insertFileUrl=async (data)=>{
    try {
        const [results, metadata] = await sequelize.query(`INSERT INTO file (url,file_hash)VALUES  ("${data.url}","${data.file_hash}")`);
        return {err: ""}
    }catch (err) {
        return {err: JSON.stringify(err)}
    }

}
module.exports={
    checkFile,
    insertSliceFile,
    checkSlice,
    insertFileUrl
}
